<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Models\HhmGoods;
use App\Models\HhmGoodsSpec;
use App\Models\HhmGoodsOption;
use App\Models\Store;
use App\Services\ImageUrlService;
use Exception;

class GoodsApiController extends BaseApiController
{
    /**
     * 获取商品详情
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function detail(Request $request): JsonResponse
    {
        try {
            $goodsId = $this->getParam($request, 'goods_id') ?: $this->getParam($request, 'id');
            
            if (!$goodsId) {
                return response()->json([
                    'code' => 400,
                    'message' => '商品ID不能为空',
                    'data' => null
                ]);
            }

            // 查询商品基本信息
            $goods = HhmGoods::where('id', $goodsId)
                ->where('status', 1)
                ->where('is_deleted', 0)
                ->first();

            if (!$goods) {
                return response()->json([
                    'code' => 404,
                    'message' => '商品不存在或已下架',
                    'data' => null
                ]);
            }

            // 处理商品图片 - 收集所有相关图片
            $images = [];
            $imageSet = []; // 用于去重
            
            // 1. 添加主图
            if (!empty($goods->thumb)) {
                $processedThumb = ImageUrlService::processImageUrl($goods->thumb);
                if (!empty($processedThumb) && !in_array($processedThumb, $imageSet)) {
                    $images[] = $processedThumb;
                    $imageSet[] = $processedThumb;
                }
            }
            
            // 2. 添加轮播图
            if (!empty($goods->thumb_url)) {
                $thumbUrls = is_array($goods->thumb_url) ? $goods->thumb_url : json_decode($goods->thumb_url, true);
                if (is_array($thumbUrls)) {
                    foreach ($thumbUrls as $url) {
                        $processedUrl = ImageUrlService::processImageUrl($url);
                        if (!empty($processedUrl) && !in_array($processedUrl, $imageSet)) {
                            $images[] = $processedUrl;
                            $imageSet[] = $processedUrl;
                        }
                    }
                }
            }

            // 处理详情图片（detail_url）
            $detailImages = [];
            if (!empty($goods->detail_url)) {
                $detailUrls = is_array($goods->detail_url) ? $goods->detail_url : json_decode($goods->detail_url, true);
                if (is_array($detailUrls)) {
                    foreach ($detailUrls as $url) {
                        $processedUrl = ImageUrlService::processImageUrl($url);
                        if (!empty($processedUrl)) {
                            $detailImages[] = $processedUrl;
                        }
                    }
                }
            }

            // 查询商品规格
            $specs = [];
            if ($goods->has_option) {
                $specs = HhmGoodsSpec::where('goods_id', $goodsId)
                    ->with(['items' => function($query) {
                        $query->orderBy('display_order', 'asc');
                    }])
                    ->orderBy('display_order', 'asc')
                    ->get()
                    ->map(function($spec) use (&$images, &$imageSet) {
                        $items = $spec->items->map(function($item) use (&$images, &$imageSet) {
                            $itemThumb = ImageUrlService::processImageUrl($item->thumb);
                            
                            // 3. 添加规格项图片到轮播图
                            if (!empty($itemThumb) && !in_array($itemThumb, $imageSet)) {
                                $images[] = $itemThumb;
                                $imageSet[] = $itemThumb;
                            }
                            
                            return [
                                'id' => $item->id,
                                'title' => $item->title,
                                'thumb' => $itemThumb,
                                'color_value' => $item->color_value,
                            ];
                        })->toArray();
                        
                        return [
                            'id' => $spec->id,
                            'title' => $spec->title,
                            'display_type' => $spec->display_type,
                            'is_required' => $spec->is_required,
                            'items' => $items
                        ];
                    })
                    ->toArray();
            }

            // 查询商品SKU选项
            $options = [];
            if ($goods->has_option) {
                $options = HhmGoodsOption::where('goods_id', $goodsId)
                    ->where('is_enabled', 1)
                    ->orderBy('display_order', 'asc')
                    ->get()
                    ->map(function($option) use (&$images, &$imageSet) {
                        $optionThumb = ImageUrlService::processImageUrl($option->thumb);
                        
                        // 4. 添加SKU图片到轮播图
                        if (!empty($optionThumb) && !in_array($optionThumb, $imageSet)) {
                            $images[] = $optionThumb;
                            $imageSet[] = $optionThumb;
                        }
                        
                        return [
                            'id' => $option->id,
                            'title' => $option->title,
                            'thumb' => $optionThumb,
                            'price' => $option->product_price,
                            'market_price' => $option->market_price,
                            'stock' => $option->stock - $option->withhold_stock, // 可用库存
                            'specs' => $option->specs,
                            'spec_titles' => $option->spec_titles,
                            'weight' => $option->weight,
                            'goods_sn' => $option->goods_sn,
                            'product_sn' => $option->product_sn,
                        ];
                    })
                    ->toArray();
            }

            // 计算总销量
            $totalSales = ($goods->show_sales ?? 0) + ($goods->real_sales ?? 0) + ($goods->virtual_sales ?? 0);

            // 查询门店信息
            $storeInfo = null;
            if ($goods->store_id) {
                $store = Store::where('id', $goods->store_id)->first();
                if ($store) {
                    $storeInfo = [
                        'id' => $store->id,
                        'name' => $store->store_name,
                        'address' => $store->address,
                        'phone' => $store->store_phone ?? $store->mobile,
                        'province' => $store->province,
                        'city' => $store->city,
                        'district' => $store->district,
                    ];
                }
            }

            // 处理时间字段（兼容整型时间戳和Carbon对象）
            $createdAt = '';
            $updatedAt = '';
            
            if ($goods->created_at) {
                if (is_numeric($goods->created_at)) {
                    $createdAt = date('Y-m-d H:i:s', $goods->created_at);
                } elseif (is_object($goods->created_at)) {
                    $createdAt = $goods->created_at->format('Y-m-d H:i:s');
                }
            }
            
            if ($goods->updated_at) {
                if (is_numeric($goods->updated_at)) {
                    $updatedAt = date('Y-m-d H:i:s', $goods->updated_at);
                } elseif (is_object($goods->updated_at)) {
                    $updatedAt = $goods->updated_at->format('Y-m-d H:i:s');
                }
            }

            // 记录收集到的图片信息
            \Log::info('[商品详情] 图片收集完成', [
                'goods_id' => $goods->id,
                'total_images' => count($images),
                'images' => $images
            ]);
            
            // 处理 content 字段中的图片路径
            $processedContent = $goods->content;
            if (!empty($processedContent)) {
                // 使用正则表达式匹配所有 img 标签中的 src 属性（支持单引号和双引号）
                $processedContent = preg_replace_callback(
                    '/<img[^>]+src=(["\'])([^"\']+)\1[^>]*>/i',
                    function($matches) {
                        $quote = $matches[1]; // 引号类型（单引号或双引号）
                        $src = $matches[2]; // 图片路径
                        // 如果是相对路径，转换为完整URL
                        if (strpos($src, 'http') !== 0 && strpos($src, '//') !== 0) {
                            // 处理相对路径，如 ../storage/ 或 storage/
                            $cleanSrc = preg_replace('#^\.\.?[/\\\]+#', '', $src); // 移除开头的 ../ 或 ./
                            $cleanSrc = ltrim($cleanSrc, '/\\');
                            $processedSrc = ImageUrlService::processImageUrl($cleanSrc);
                            // 替换原 src 值
                            return str_replace($src, $processedSrc, $matches[0]);
                        }
                        // 如果已经是完整URL，直接返回
                        return $matches[0];
                    },
                    $processedContent
                );
            }
            
            // 构建返回数据
            $data = [
                'id' => $goods->id,
                'title' => $goods->title,
                'alias' => $goods->alias,
                'thumb' => ImageUrlService::processImageUrl($goods->thumb),
                'images' => $images,
                'video_url' => $goods->video_url,
                'detail_url' => $detailImages, // 详情图片数组
                'price' => $goods->price,
                'market_price' => $goods->market_price,
                'cost_price' => $goods->cost_price,
                'stock' => $goods->stock,
                'sku' => $goods->sku,
                'description' => $goods->description,
                'content' => $processedContent,
                'has_option' => $goods->has_option,
                'option_count' => $goods->option_count,
                'specs' => $specs,
                'options' => $options,
                'weight' => $goods->weight,
                'volume' => $goods->volume,
                'goods_sn' => $goods->goods_sn,
                'product_sn' => $goods->product_sn,
                'is_new' => $goods->is_new,
                'is_hot' => $goods->is_hot,
                'is_discount' => $goods->is_discount,
                'is_recommand' => $goods->is_recommand,
                'sales' => $totalSales,
                'comment_num' => $goods->comment_num,
                'min_buy' => $goods->min_buy,
                'max_buy' => $goods->max_buy,
                'is_limit' => $goods->is_limit,
                'store_id' => $goods->store_id,
                'store_info' => $storeInfo,
                'created_at' => $createdAt,
                'updated_at' => $updatedAt,
            ];

            return response()->json([
                'code' => 200,
                'message' => '获取成功',
                'data' => $data
            ]);

        } catch (Exception $e) {
            \Log::error('商品详情查询失败', [
                'goods_id' => $goodsId ?? 'unknown',
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 500,
                'message' => '获取失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 获取商品列表
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function list(Request $request): JsonResponse
    {
        try {
            $page = max(1, (int) $this->getParam($request, 'page', 1));
            $limit = max(1, min(50, (int) $this->getParam($request, 'limit', 10)));
            $storeId = $this->getParam($request, 'store_id');
            $categoryId = $this->getParam($request, 'category_id');
            $keyword = trim($this->getParam($request, 'keyword', ''));

            // 构建查询
            $query = HhmGoods::where('status', 1)
                ->where('is_deleted', 0);

            // 店铺筛选
            if ($storeId) {
                $query->where('store_id', $storeId);
            }

            // 分类筛选
            if ($categoryId) {
                $query->where(function($q) use ($categoryId) {
                    $q->where('category_id_1', $categoryId)
                      ->orWhere('category_id_2', $categoryId);
                });
            }

            // 关键词搜索
            if (!empty($keyword)) {
                $query->where(function($q) use ($keyword) {
                    $q->where('title', 'like', "%{$keyword}%")
                      ->orWhere('alias', 'like', "%{$keyword}%")
                      ->orWhere('description', 'like', "%{$keyword}%");
                });
            }

            // 分页查询
            $total = $query->count();
            $goods = $query->orderBy('display_order', 'desc')
                ->orderBy('id', 'desc')
                ->offset(($page - 1) * $limit)
                ->limit($limit)
                ->get();

            // 格式化数据
            $list = $goods->map(function($item) {
                $totalSales = ($item->show_sales ?? 0) + ($item->real_sales ?? 0) + ($item->virtual_sales ?? 0);
                
                return [
                    'id' => $item->id,
                    'title' => $item->title,
                    'thumb' => ImageUrlService::processImageUrl($item->thumb),
                    'price' => $item->price,
                    'market_price' => $item->market_price,
                    'stock' => $item->stock,
                    'sku' => $item->sku,
                    'description' => $item->description,
                    'has_option' => $item->has_option,
                    'is_new' => $item->is_new,
                    'is_hot' => $item->is_hot,
                    'is_discount' => $item->is_discount,
                    'is_recommand' => $item->is_recommand,
                    'sales' => $totalSales,
                ];
            })->toArray();

            return response()->json([
                'code' => 200,
                'message' => '获取成功',
                'data' => [
                    'list' => $list,
                    'pagination' => [
                        'total' => $total,
                        'page' => $page,
                        'limit' => $limit,
                        'total_pages' => ceil($total / $limit),
                    ]
                ]
            ]);

        } catch (Exception $e) {
            \Log::error('商品列表查询失败', [
                'error' => $e->getMessage(),
                'params' => $request->all()
            ]);
            
            return response()->json([
                'code' => 500,
                'message' => '获取失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
}

